package com.kou.filter;

import com.alibaba.fastjson.JSONObject;
import com.kou.pojo.User;
import com.kou.utils.Base64Utils;
import com.kou.utils.Constants;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author SteinY
 * @create 2022-03-25 10:18
 * @description:
 */
@WebFilter("/*")
public class LoginFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    //从cookie中获取两周之内的用户信息
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        Cookie[] cookies = request.getCookies();
        if (cookies!=null&&cookies.length>0){
            for (Cookie cookie : cookies) {

                if (cookie.getName().equals(Constants.AUTO_NAME)){
                    String value = cookie.getValue();
                    String json = Base64Utils.decode(value);
                    User user = JSONObject.parseObject(json, User.class);
                    request.getSession().setAttribute("loginUser",user);

                }
            }
        }
        //放行！！
        filterChain.doFilter(request,response);
    }

    @Override
    public void destroy() {

    }
}
